﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cofe.Core.Logger;

namespace Cofe.Data
{
    public class EFEventRepository : IEventRepository
    {
        #region Constructor

        internal EFEventRepository(EFRepository repository)
        {
            _repository = repository;
        }
        
        #endregion

        #region Methods

        public void WriteEvents(params IEventLog<CofeSystemEventArgs>[] events) 
        {
            foreach (var e in events)
            {
                Guid entryId = _repository.Context.DBEntries
                    .Where(de => de.ParseName == e.EventArgs.FullParsePath)
                        .Select(de => de.Id).FirstOrDefault();
                _repository.Context.Entry(CofeSystemEventLog.FroEventLog(e, entryId)).State = System.Data.EntityState.Added;
            }
        }

        public IEnumerable<CofeSystemEventLog> FindEvents(EventSearchParam param = null)
        {
            var query = _repository.Context.CofeSystemEventLogs.AsQueryable();

            if (param.StartIdx.HasValue)
                query = query.Where(e => e.Id >= param.StartIdx.Value);

            if (param.EndIdx.HasValue)
                query = query.Where(e => e.Id <= param.EndIdx.Value);

            if (param.StartTime.HasValue)
                query = query.Where(e => e.Time >= param.StartTime.Value);

            if (param.EndTime.HasValue)
                query = query.Where(e => e.Time <= param.EndTime.Value);

            return query.ToList();
        }
        
        #endregion

        #region Data

        EFRepository _repository;
        #endregion

        #region Public Properties
        
        #endregion

    }
}
